package com.dsiab.manageService.schedule;

import com.dsiab.manageService.entity.PagesDto;
import com.dsiab.manageService.mail.MailSenderBoot;
import com.dsiab.manageService.mapper.AdminDao;
import com.dsiab.manageService.mapper.ScheduleCron;
import com.dsiab.manageService.mapper.WebStatsDao;
import com.dsiab.manageService.service.AccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@EnableScheduling
@Slf4j
public class ScheduleDymic implements SchedulingConfigurer {

    @Autowired
    ScheduleCron scheduleCron;

    @Autowired
    AccountService accountService;

    @Autowired
    MailSenderBoot mailSenderBoot;

    @Autowired
    WebStatsDao webStatsDao;

    @Autowired
    AdminDao adminDao;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(() -> getBakToMail(),triggerContext -> {
            String cron = scheduleCron.getCron(1);
            if (cron.isEmpty()){
                System.out.println("cron is null");
            }
            return new CronTrigger(cron).nextExecution(triggerContext);
        });
        taskRegistrar.addTriggerTask(() -> saveEveryDayViews(),triggerContext -> {
            String cron = scheduleCron.getCron(2);
            if (cron.isEmpty()){
                System.out.println("cron is null");
            }
            return new CronTrigger(cron).nextExecution(triggerContext);
        });
        taskRegistrar.addTriggerTask(() -> generateUid(),triggerContext -> {
            String cron = scheduleCron.getCron(3);
            if (cron.isEmpty()){
                System.out.println("cron is null");
            }
            return new CronTrigger(cron).nextExecution(triggerContext);
        });
    }
    public void getBakToMail() {
        // 每晚20：30点半备份数据库文件到邮件
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String currDate = (String) sdf.format(d);

        Map siteInfo = accountService.getSiteInfo();
        String realPath = (String) siteInfo.get("bakRealUrl");
        File dir =new File(realPath);//遍历文件夹下的所有内容
        File[] files=dir.listFiles();   //列出所有的子文件
        if (files == null){
            log.info("找不到备份文件");
            return;
        }
        for(File file :files) {
            if(file.isFile()){
                //如果是文件，则输出文件名字
                log.info("fileName===" + file.getName());
                String fileName = file.getName();
                String filePath = file.toString();
                int index = fileName.indexOf(currDate);
                if (index > -1){
                    try {
                        mailSenderBoot.sendAttachmentsMail((String) siteInfo.get("siteEmail"), "备份文件", "备份数据库文件到邮箱", filePath);
                    } catch (Exception e){
                        log.info("发送失败：" + e);
                    }
                    log.info("发送成功");
                }
            }
        }
    }

    public void saveEveryDayViews() {
        // 每1个小时更新统计数据
        Map map = new HashMap();
        // 查所有访问量
        map.put("allViews", webStatsDao.getAllPagesViews());
        // 查所有文章
        map.put("allpages", webStatsDao.getAllPagesCount());
        // 查当天数据
        map.put("dayViews",webStatsDao.getViewsByDate());
        // 查当天访问ip
        map.put("dayIp",webStatsDao.getViewsByIp());
        // 查所当天访问来源
        map.put("referrer", webStatsDao.getReferrerNowDay());
        // 查所当天访问文章
        map.put("viewAddress", webStatsDao.getPostView());

        webStatsDao.delExistViews();

        webStatsDao.saveEveryDayViews(map);
    }
    public void generateUid() {
      List<PagesDto> list = adminDao.getCurrentDayPost();
      for (PagesDto pagesDto : list){
          if (pagesDto.getUid() == null){
              adminDao.updateUid(pagesDto.getId(),UUID.randomUUID().toString());
          }
      }
    }
}
